package com.polaris.server.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.polaris.security.util.JwtTokenUtil;
import com.polaris.server.dto.JobQueryParam;
import com.polaris.server.pojo.SysJob;
import com.polaris.server.mapper.SysJobMapper;
import com.polaris.server.service.ISysJobService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 岗位 服务实现类
 * </p>
 *
 * @author polaris
 * @since 2021-05-19
 */
@Service
public class SysJobServiceImpl extends ServiceImpl<SysJobMapper, SysJob> implements ISysJobService {

    private final SysJobMapper jobMapper;
    private final JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    public SysJobServiceImpl(SysJobMapper jobMapper, JwtTokenUtil jwtTokenUtil) {
        this.jobMapper = jobMapper;
        this.jwtTokenUtil = jwtTokenUtil;
    }

    /**
     * 获取所有的职位
     *
     * @return
     */
    @Override
    public List<SysJob> queryAll() {
        return jobMapper.selectList(new QueryWrapper<>());
    }

    /**
     * 通过id更新职位信息
     *
     * @param id
     * @param queryParam
     * @return
     */
    @Override
    public SysJob updateJob(Long id, JobQueryParam queryParam, HttpServletRequest request) {
        if(StringUtils.hasText(queryParam.toString())){
            Map<String, Object> map = BeanUtil.beanToMap(queryParam, true, false);
            SysJob job = jobMapper.selectById(id);
            if(map.get("name")!=null){
                job.setName((String) map.get("name"));
            }
            if(map.get("enabled")!=null){
                job.setEnabled((Boolean) map.get("enabled"));
            }
            if(map.get("jobSort")!=null){
                job.setJobSort((Integer) map.get("jobSort"));
            }
            String header = request.getHeader(this.tokenHeader);
            String authToken = header.substring(this.tokenHead.length());
            String userNameFromToken = jwtTokenUtil.getUserNameFromToken(authToken);
            job.setCreateBy(userNameFromToken);
            jobMapper.updateById(job);
            return job;
        }
        return null;
    }
}
